package org.sjs.dreamfly.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import org.sjs.dreamfly.R

class TitleBar : FrameLayout {

    interface OnActionListener {
        fun onBackButtonClick()
    }

    private var onActionListener: OnActionListener? = null
    private var title: String? = null
    private var blackStyle = false
    private var backBtnVisible = true
    private var wrapperView: View
    private var btnBackView: ImageView
    private var titleView: TextView

    constructor(context: Context) : this(context, null, -1, -1)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, -1, -1)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(context, attrs, defStyleAttr, -1)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        LayoutInflater.from(context).inflate(R.layout.widget_layout_title_bar, this).apply {
            wrapperView = findViewById(R.id.root_view)
            btnBackView = findViewById(R.id.btn_back)
            titleView = findViewById(R.id.title)
        }
    }

    fun setTitle(title: String) {
        this.title = title
        titleView.text = title
    }

    fun setOnBackListener(listener: OnActionListener) {
        this.onActionListener = listener
        btnBackView.setOnClickListener { listener.onBackButtonClick() }
    }

    fun setStyle(black: Boolean) {
        if (black != this.blackStyle) {
            this.blackStyle = black
            if (black) {
                wrapperView.background = null
                btnBackView.setImageResource(R.mipmap.btn_back_white)
                titleView.setTextColor(resources.getColor(R.color.white))
            } else {
                wrapperView.setBackgroundResource(R.drawable.bg_line_bottom_black)
                btnBackView.setImageResource(R.mipmap.btn_back_black)
                titleView.setTextColor(resources.getColor(R.color.black))
            }
        }
    }

    fun setBackButtonVisible(visible: Boolean) {
        btnBackView.visibility = if (visible) View.VISIBLE else View.GONE
    }
}